<template>
  <el-dialog :visible.sync="dialogVisible" title="更改头像" width="400px">
    <div class="avatar-container">
      <h3>当前头像</h3>
      <img :src="currentAvatarUrl" alt="Current Avatar" class="current-avatar" />
    </div>

    <div class="upload-section">
      <h3>上传新头像</h3>
      <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :before-upload="handleBeforeUpload"
          :http-request="handleUpload"
      >
        <el-button type="primary">选择图片</el-button>
      </el-upload>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="submitNewAvatar">确认</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElDialog, ElButton, ElUpload } from 'element-plus';
import {UploadApi} from '@/apis/uploadApi.js'; // 假设你的 UploadApi 在此路径下

// 获取 userInfo 对象中的 avatarUrl
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
const currentAvatarUrl = ref(userInfo.avatarUrl || '');

// 控制对话框显示状态
const dialogVisible = ref(false);

// 新上传的头像 URL
const newAvatarUrl = ref('');

// 打开对话框
function openDialog() {
  dialogVisible.value = true;
}

// 关闭对话框
function closeDialog() {
  dialogVisible.value = false;
}

// 处理上传前的操作
function handleBeforeUpload(file) {
  const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 20;

  if (!isJPGorPNG) {
    ElMessage.error('只能上传 JPG 或 PNG 格式的图片!');
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 20MB!');
  }
  return isJPGorPNG && isLt2M;
}

// 自定义上传逻辑
async function handleUpload(uploadFile) {
  try {
    const response = await UploadApi.uploadImage(uploadFile.file);
    console.log('成功请求上传图片', response);
    newAvatarUrl.value = response.data.url; // 这里假设响应中包含新头像的 URL
  } catch (error) {
    ElMessage.error(`上传失败: ${error.message}`);
  }
}

// 提交新头像
function submitNewAvatar() {
  if (newAvatarUrl.value) {
    // 更新本地存储中的头像 URL
    userInfo.avatarUrl = newAvatarUrl.value;
    localStorage.setItem('userInfo', JSON.stringify(userInfo));
    currentAvatarUrl.value = newAvatarUrl.value;
    closeDialog();
    // 这里可以添加其他操作，比如更新后端数据库中的头像 URL
    console.log('新头像已提交:', newAvatarUrl.value);
  } else {
    ElMessage.warning('请先上传头像');
  }
}

// 暴露给父组件的方法
defineExpose({
  openDialog,
});
</script>

<style scoped>
.avatar-container {
  text-align: center;
  margin-bottom: 20px;
}

.current-avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
}

.upload-section {
  text-align: center;
}
</style>
